
import { CapacitorHttp } from '@capacitor/core';

export interface ModelProps {
    id: string;
    uri?: string;
    title: string;
    url: string;
    tags?: string;
    status?: number;
}

export default class Api {
    static prefix = "http://onceio.top/es"; //http://onceio.top
    static async create() {
        let url = Api.prefix + '/model3d';
        let response = await CapacitorHttp.put({
            url,
            data: {
                "mappings": {
                    "properties": {
                        "id": {
                            "type": "text",
                            "store": true,
                            "index": "true"
                        },
                        "title": {
                            "type": "text",
                            "store": true,
                            "index": "true",
                            "analyzer": "standard"
                        },
                        "uri": {
                            "type": "text",
                            "store": true,
                            "index": "false"
                        },
                        "tags": {
                            "type": "text",
                            "store": true,
                            "index": "true",
                            "analyzer": "standard"
                        }
                    }

                }
            }
        });

        return response;
    }

    static async search(query: string, from: number, size: number) {
        let url = Api.prefix + '/model3d/_search';

        let data = query ? {
            "query": {
                "query_string": {
                    "query": query
                }
            }
        } : {};

        let resp = await CapacitorHttp.post({
            url,
            headers: { "Content-Type": 'application/json' },
            params: {
                "from": from + "",
                "size": size + "",
            },
            data
        });

        let rows = new Array<ModelProps>();

        if (resp.data.hits) {
            for (let hit of resp.data.hits.hits) {
                let item = hit._source;
                let row = { id: item.id, url: `//onceio.top/glb/${item.id}.glb`, title: item.title, tags: item.tags }
                rows.push(row);
            }
        }
        return rows;
    }



    static async put(model: ModelProps) {
        let url = Api.prefix + `/model3d/_doc/${model.id}`;
        let resp = await CapacitorHttp.post({
            url,
            data: model,
            headers: {
                "Content-Type": "application/json"
            }
        });
        return resp.data;
    }
}